package cn.itsource.controller;

import cn.itsource.annotation.PreAuthorize;
import cn.itsource.domain.Comment;
import cn.itsource.service.ICommentService;
import cn.itsource.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/comment")
@Api(tags = "评论接口")
public class CommentController {
    @Autowired
    private ICommentService commentService;
    /**
     * 增加/修改
     * @param
     * @return
     */
    @ApiOperation(value = "增加/修改")
    @PutMapping
    @PreAuthorize(descs = "评论增加/修改",name = "评论增加/修改",sn = "comment:addORupdate")
    public R addORupdateComment(@RequestBody Comment comment){
        try {
            if (comment.getId() == null){
                commentService.add(comment);
            }else {
                commentService.update(comment);
            }
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.fail();
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    @PreAuthorize(descs = "评论删除",name = "评论删除",sn = "comment:del")
    public R delComment(@PathVariable("id") String id){
        try {
            commentService.del(id);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "查询所有评论")
    @GetMapping("/{id}")
    @PreAuthorize(descs = "评论查询所有",name = "评论查询所有",sn = "comment:getAll")
    public R getAllComment(@PathVariable("id") Long id){
        try {
            return R.ok(commentService.findByArticleId(id));
        }catch (Exception e){
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }
}
